<template>
	<view class="direct-message-wrapper">
		<view class="content-wrapper">
			<scroll-view  scroll-y="true" class="scroll-Y" style="height: calc(100vh - 100px)" @scrolltoupper="upper" :scroll-into-view="scrollInntoView">
				<view class="message-item" :class="[item.sendUserId === $store.state.userInfo.id?'item-self':'']" v-for="(item, index) in list" :key="index">
					<u-avatar v-if="item.sendUserId !== $store.state.userInfo.id" level-size="90" level-icon="/static/img/community/ic_daka.png"
						:show-level="doctorInfo.starFlag" mode="circle" :src="img_url + avatar" img-mode="aspectFill">
					</u-avatar>
					<view class="item-right" >
						<view class="text-desc">
							<text v-if="item.contentType =='1'">{{item.content}}</text> 
							<img class="images-direct" v-if="item.contentType =='2'" :src="`${img_url}${item.content}`" alt="" srcset="">
						</view>
						<view class="time">
							{{item.sendTime}}
						</view>
					</view>
						<u-avatar  v-if="item.sendUserId === $store.state.userInfo.id" level-size="90" level-icon="/static/img/community/ic_daka.png"
							:show-level="starFlag" mode="circle" :src="userAvater" img-mode="aspectFill">
						</u-avatar>
				</view>
				<view class="input-id" id="inputID">1322313</view>
				<view class="input-id" id="inputID1">1322313</view>
			</scroll-view>
		</view>
		<view class="input-wrapper"  >
			<input  @confirm="onComment('1', content)" placeholder="请输入" border-color="#fff" height="60" class="input-style" v-model="content" type="text" :border="false" />
			<u-icon @click="chooseFile" class="photo-image" name="photo" color="#3D92CA" size="60"></u-icon>
			<!-- <u-upload :action="action"  max-count="6" :show-upload-list="false"></u-upload> -->
		</view>
	</view>
</template>

<script>
import apis from '@/apis.js'
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex'
	export default {
		data() {
			return {
				action: "/qts_api/upload/upload",
				userAvater: '',
				id: "",
				authorId: "",
				content: "",
				form: {
					pageNo: 1,
					pageSize: 10
				},
				list: [],
				doctorInfo: {},
				starFlag: false,
				avatar: '',
				scrollInntoView: '',
				copyList: "",
				timer: null
			};
		},
		computed: {
			...mapState([ 'TOKEN', 'img_url', 'userInfo']),
			docterAvater() {
				return `${this.img_url}${this.doctorInfo.avatar}`
			},
		},
		onHide() {
			clearInterval(this.timer)
			this.timer = null
			console.log("onHide")
		},
		onload() {

		},
		destroyed() {
			clearInterval(this.timer)
			this.timer = null
			console.log("onHide")
			
		},
		onShow() {
			clearInterval(this.timer)
			this.form.pageNo =1
			this.list = []
			// this.reportShow = false
			this.id = this.$route.query.id 
			this.avatar = this.$route.query.avatar
			this.starFlag = this.$store.state.userInfo.starFlag == "1" ? true : false
			uni.setNavigationBarTitle({
				title: this.$route.query.name
			})
			this.getDoctor()
			this.getList()
			this.setIntervalList()
		},
		methods: {
			// 定时器
			setIntervalList() {
				this.timer = setInterval(() => {
					if (this.copyList) {
						this.getInterList()
					}
				}, 3000);
			},
			// 这个是右边
			getDoctor() {
				this.$http.get(apis.user_detail+'/'+ this.id).then(res => {
					if (res.data.code === 200) {
						this.doctorInfo = res.data.result
						this.doctorInfo.starFlag = this.doctorInfo.starFlag == "1" ? true: false
						// console.log("")
						this.userAvater = `${this.img_url}${this.$store.state.userInfo.avatar}`
						
					}
				})
			},
			chooseFile() {
				let that = this
				uni.chooseImage({
				  count: 1, //默认100
				    success:  (res) => {
								let tempFilePaths = res.tempFilePaths
								let tempFiles = res.tempFiles
								console.log(res)
								uni.uploadFile({
										url: apis.uploadImage, //仅为示例，非真实的接口地址
										filePath: tempFilePaths[0],
										name: 'file',
										header: {
											"Authorization": that.TOKEN
										},
										success: (uploadFileRes) => {
												let data = JSON.parse(uploadFileRes.data)
												// let param = {
												// 	attachName: tempFiles[0].name,
												// 	attachUrl: data.message
												// }
												that.content = ""
												that.onComment("2", data.message)
												
												console.log("data", data)
												// that.attachList.push(param)
										}
								});
				    }
				});
			},
			upper() {
				this.form.pageNo = this.form.pageNo + 1
				this.getList()
			},
			// 无限加载 利用公共方法判断
			onReachBottom() {
				// this.form.pageNo = this.form.pageNo + 1
				console.log("onReachBottom")
				// this.getList()
			},
			getInterList() {
				this.$http.get(apis.news_record_list, {
					letterUserId: this.id,
					pageNo: 1,
					pageSize: this.form.pageSize
				}).then(res => {
					if (res.data.code === 200) {
							
							if (this.copyList !== JSON.stringify(res.data.result.records) && this.copyList) {
								this.list = res.data.result.records
								this.form.pageNo = 1
								console.log("123243")
								this.$nextTick(() => {
									this.scrollInntoView = 'inputID'
								})
							}
						
					}
				})
			},
			getList() {
				console.log("psdf", this.form.pageNo)
				this.$http.get(apis.news_record_list, {
					letterUserId: this.id,
					pageNo: this.form.pageNo,
					pageSize: this.form.pageSize
				}).then(res => {
					if (res.data.code === 200) {
						if (this.form.pageNo === 1) {
							this.list = []
							// [4,3,2,1] 
							this.list = res.data.result.records
							this.copyList = JSON.stringify(res.data.result.records)
							console.log("123")
							setTimeout(() => {
								if (this.scrollInntoView == 'inputID') {
									this.scrollInntoView = 'inputID1'
								} else {
									this.scrollInntoView = 'inputID'
								}
							}, 80);
						} else { 
							// [9,8,7,6] 
							let  reverList = res.data.result.records.reverse()
							reverList.forEach((item) => {
								this.list.unshift(item)
							})
						}
						
						// this.list = this.list.unshift(reverList)
						// this.list = this.list.concat(res.data.result.records)
						
					}
				})
			},
			onComment(contentType, content) {
				// let desc = ""
				// if (contentType == "2") {
				// 	desc = content
				// } else {
				// 	desc = this.content
				// }
				this.$http.post(apis.news_record_send, { 
					"content": content,
					"contentType": contentType || "1",//消息内容类型（1：文本；2：图片；3：视频；4：音乐）
					"receiveUserId": this.id
				 }).then(res => {
					if (res.data.code === 200) {
						this.content = ""
						var myDate = new Date();
						let month = Number(myDate.getMonth()) + 1
						this.list.push({
							content: content,
							contentType: contentType,
							sendTime: `${myDate.getFullYear()}-${month}-${myDate.getDate()} ${myDate.getHours()}:${myDate.getMinutes()}:${myDate.getSeconds()}`,
							sendUserId: this.$store.state.userInfo.id
						
						})
						setTimeout(() => {
							if (this.scrollInntoView == 'inputID') {
								this.scrollInntoView = 'inputID1'
							} else {
								this.scrollInntoView = 'inputID'
							}
							}, 80);
						// this.list = []
						this.form.pageNo = 0
						// this.getList()
						// this.$refs.uTips.show({
						// 	title: '发送成功',
						// 	type: 'success',
						// 	duration: '2300'
						// })
						// uni.showToast({
						// 	title: "发送成功",
						// 	icon: "none",
						// });
					}
				})
			},

			
		}
	}
</script>

<style scoped lang="scss">
	.input-id{
		opacity: 0;
	}
.direct-message-wrapper {
	box-sizing: border-box;
		background: #E9EBF4;
	.content-wrapper {
		height: calc(100vh - 150rpx);
		// height: 100vh;
		padding: 0 34rpx;
		padding-top: 50rpx;
		display: flex;
		// flex-direction: column-reverse;
		flex-direction: column;
		overflow: auto;
		.message-item {
			display: flex;
			align-items: flex-start;
			margin-bottom: 62rpx;
			.item-right {
				margin-left: 16rpx;
				margin-top: 48rpx;
				.text-desc {
					background: #A4CDE8;
					opacity: 1;
					border-radius: 16rpx;
					padding: 34rpx 22rpx;
					font-size: 32rpx;
					font-family: SimHei;
					font-weight: 400;
					color: #4D5B80;
					opacity: 1;
					line-height: 42rpx;
					margin-bottom: 16rpx;
					word-break: break-all;
				}
				.time {
					font-size: 24rpx;
					font-family: SimHei;
					font-weight: 400;
					line-height: 32rpx;
					color: #949494;
					opacity: 1;
				}
				
			}
		}
		.item-self {
			justify-content: flex-end;
			.item-right {
				margin-right: 16rpx;
				.text-desc {
					background: #FFFFFF;
					color: #4D5B80;
				}
			}
		}
	}
	.input-wrapper {
		display: flex;
		align-items: center;
		margin-right: 22rpx;
		height: 60rpx;
		.input-style {
			background: #fff;
			background: #FFFFFF;
			opacity: 1;
			border-radius: 8rpx;
			padding-left: 16rpx;
			width: 100%;
			height: 60rpx;
			line-height: 60rpx;
			.uni-input-input {
				padding-left: 15rpx;
			}
		}
		.photo-image {
			margin-left: 30rpx;
		}
	}
}
.images-direct {
	width: 120rpx;
	height: 120rpx;
}
</style>
